package com.icongyou.enterprise.talent_pool.service;

import com.icongyou.enterprise.data_aggregation.entity.AssignmentEntity;
import com.icongyou.enterprise.data_aggregation.service.DataAggregationService;
import com.icongyou.enterprise.talent_pool.entity.AssignmentTagEntity;
import com.icongyou.enterprise.talent_pool.mapper.AssignmentTagMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class TagRelevanceCalculationService {

    private final AssignmentTagMapper assignmentTagMapper;
    private final AIModelService aiModelService;
    private final DataAggregationService dataAggregationService;
    private final AssignmentWeightService assignmentWeightService;

    /**
     * 为新增标签计算它与所有截止任务的关联度
     */
    public void calculateTagForAllAssignments(String tagId, String tagName) {

        try {
            // 直接获取所有截止任务信息（一次性查询）
            List<AssignmentEntity> allAssignments = dataAggregationService.getAllCompletedAssignments();

            // 分批处理，每批50个任务
            int batchSize = 50;
            int totalProcessed = 0;
            List<AssignmentTagEntity> allAssignmentTags = new ArrayList<>();

            for (int i = 0; i < allAssignments.size(); i += batchSize) {
                int end = Math.min(i + batchSize, allAssignments.size());
                List<AssignmentEntity> batchAssignments = allAssignments.subList(i, end);

                // 构建任务描述映射
                Map<String, String> batchAssignmentDescriptions = new HashMap<>();
                for (AssignmentEntity assignment : batchAssignments) {
                    batchAssignmentDescriptions.put(assignment.getAssignmentId(), assignment.getDescription());
                }

                // 批量计算关联度
                Map<String, Double> batchRelevanceMap = aiModelService.batchCalculateTagRelevance(
                        tagName, batchAssignmentDescriptions);

                // 批量创建关联实体
                for (Map.Entry<String, Double> entry : batchRelevanceMap.entrySet()) {
                    String assignmentId = entry.getKey();
                    Double relevance = entry.getValue();
                    Double assignmentWeight = assignmentWeightService.calculateAssignmentImportanceWeight(assignmentId);

                    AssignmentTagEntity assignmentTag = createAssignmentTagEntity(
                            assignmentId, tagId, relevance, assignmentWeight);
                    allAssignmentTags.add(assignmentTag);
                }

                totalProcessed += batchAssignments.size();

                // 批量保存
                if (allAssignmentTags.size() >= 100) {
                    saveAssignmentTagsBatch(allAssignmentTags);
                    allAssignmentTags.clear();
                }
            }

            // 保存剩余数据
            if (!allAssignmentTags.isEmpty()) {
                saveAssignmentTagsBatch(allAssignmentTags);
            }


        } catch (Exception e) {
            throw new RuntimeException("计算标签与所有任务关联度失败", e);
        }
    }

    /**
     * 基于关键词匹配计算关联度（极简降级方案）
     */
    public Double calculateRelevanceByKeyword(String tagName, String text) {
        if (text == null || text.trim().isEmpty() || tagName == null || tagName.trim().isEmpty()) {
            return 0.0;
        }

        String lowerTagName = tagName.toLowerCase().trim();
        String lowerText = text.toLowerCase();

        // 1. 直接完全匹配 - 最高分数
        if (lowerText.contains(lowerTagName)) {
            return 0.8;
        }

        // 2. 极简分词匹配 - 只按空格分词，不考虑中文分词
        String[] tagWords = lowerTagName.split("\\s+");
        int matchCount = 0;
        int totalValidWords = 0;

        for (String word : tagWords) {
            // 只考虑长度>=2的词
            if (word != null && word.length() >= 2) {
                totalValidWords++;
                if (lowerText.contains(word)) {
                    matchCount++;
                }
            }
        }

        // 如果没有有效词汇，返回0
        if (totalValidWords == 0) {
            return 0.0;
        }

        // 根据匹配比例返回分数
        double matchRatio = (double) matchCount / totalValidWords;

        if (matchRatio >= 0.8) {
            return 0.7; // 高匹配率
        } else if (matchRatio >= 0.5) {
            return 0.5; // 中等匹配率
        } else if (matchRatio >= 0.3) {
            return 0.3; // 低匹配率
        } else {
            return 0.0; // 无有效匹配
        }
    }

    /**
     * 批量保存任务标签关联
     */
    public void saveAssignmentTagsBatch(List<AssignmentTagEntity> assignmentTags) {
        try {
            if (assignmentTags.isEmpty()) {
                return;
            }

            // 先删除这些任务已有的关联（针对相同的标签）
            List<String> assignmentIds = assignmentTags.stream()
                    .map(AssignmentTagEntity::getAssignmentId)
                    .distinct()
                    .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

            String tagId = assignmentTags.get(0).getTagId();
            deleteAssignmentTagsByTagAndAssignments(tagId, assignmentIds);

            // 插入新的关联
            assignmentTagMapper.batchInsertAssignmentTags(assignmentTags);

        } catch (Exception e) {
            throw new RuntimeException("批量保存任务标签关联失败", e);
        }
    }

    /**
     * 删除指定标签和任务集的关联
     */
    private void deleteAssignmentTagsByTagAndAssignments(String tagId, List<String> assignmentIds) {
        if (assignmentIds.isEmpty()) {
            return;
        }

        int deletedCount = assignmentTagMapper.deleteByTagIdAndAssignmentIds(tagId, assignmentIds);
    }

    /**
     * 创建任务标签关联实体
     */
    public AssignmentTagEntity createAssignmentTagEntity(String assignmentId, String tagId,
                                                         Double relevance, Double assignmentWeight) {
        AssignmentTagEntity assignmentTag = new AssignmentTagEntity();
        assignmentTag.setId(UUID.randomUUID().toString());
        assignmentTag.setAssignmentId(assignmentId);
        assignmentTag.setTagId(tagId);
        assignmentTag.setRelevance(relevance);
        assignmentTag.setAssignmentWeight(assignmentWeight);
        assignmentTag.setCalculatedTime(LocalDateTime.now());
        return assignmentTag;
    }

}